<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, View, Star, ChatDotRound } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import DefaultLayout from '@/components/layout/DefaultLayout.vue'
import { useBlogStore } from '@/store/blog'

const router = useRouter()
const blogStore = useBlogStore()

const latestBlogs = ref([])
const blogTypes = ref([])
const loading = ref(true)
const searchQuery = ref('')
const selectedType = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

onMounted(async () => {
  try {
    loading.value = true
    const [blogData, typeData] = await Promise.all([
      blogStore.fetchBlogs(1, 6),
      blogStore.fetchBlogTypes()
    ])
    latestBlogs.value = blogData.content
    blogTypes.value = typeData
  } catch (error) {
    console.error('Failed to fetch blogs', error)
  } finally {
    loading.value = false
  }
})

const goToBlogDetail = (id) => {
  console.log('跳转到博客详情，ID:', id)
  console.log('目标路径:', `/blogs/${id}`)
  router.push(`/blogs/${id}`)
}

const goToBlogsByType = (typeId) => {
  router.push({
    path: '/blogs',
    query: { type: typeId }
  })
}

// 获取博客列表
const fetchBlogs = async () => {
  try {
    const response = await axios.get('/api/blogs/published', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        query: searchQuery.value,
        typeId: selectedType.value || null
      }
    })
    latestBlogs.value = response.data.content
    total.value = response.data.total
    console.log('latestBlogs:', latestBlogs.value)
  } catch (error) {
    ElMessage.error('获取博客列表失败')
  }
}

// 获取博客分类
const fetchBlogTypes = async () => {
  try {
    const response = await axios.get('/api/blog-types')
    blogTypes.value = response.data
  } catch (error) {
    ElMessage.error('获取博客分类失败')
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchBlogs()
}

// 处理分类变化
const handleTypeChange = () => {
  currentPage.value = 1
  fetchBlogs()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchBlogs()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchBlogs()
}
</script>

<template>
  <DefaultLayout>
    <!-- 横幅区域 -->
    <section class="banner-section">
      <div class="banner-content">
        <h1 class="banner-title">分享你的想法，<br />连接更多的思想</h1>
        <p class="banner-description">
          在这里记录生活点滴，分享你的知识和见解，与他人共同成长
        </p>
        <div class="banner-actions">
          <router-link to="/blogs" class="btn btn-primary">浏览文章</router-link>
          <router-link to="/register" class="btn btn-secondary">加入我们</router-link>
        </div>
      </div>
      <div class="banner-decoration">
        <div class="decoration-circle"></div>
        <div class="decoration-square"></div>
        <div class="decoration-dots"></div>
      </div>
    </section>
    
    <!-- 博客分类 -->
    <section class="section categories-section">
      <div class="section-header">
        <h2 class="section-title">探索分类</h2>
      </div>
      <div class="categories-grid" v-if="!loading">
        <div 
          v-for="type in blogTypes" 
          :key="type.typeId" 
          class="category-card"
          @click="goToBlogsByType(type.typeId)"
        >
          <div class="category-content">
            <h3 class="category-name">{{ type.typeName }}</h3>
            <div class="category-info">
              <span class="category-author">作者: {{ type.user?.name || '未知' }}</span>
              <span class="category-count">{{ type.blogCount || 0 }} 篇文章</span>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="loading-container">
        <div class="loading-spinner"></div>
      </div>
    </section>
    
    <!-- 最新博客 -->
    <section class="section latest-blogs-section">
      <div class="section-header">
        <h2 class="section-title">最新博客</h2>
        <router-link to="/blogs" class="view-all">查看全部</router-link>
      </div>
      
      <div class="blogs-grid" v-if="!loading">
        <div 
          v-for="blog in latestBlogs" 
          :key="blog.blogId" 
          class="blog-card"
          @click="goToBlogDetail(blog.blogId)"
        >
          <div class="blog-image" :style="blog.coverImageUrl ? `background-image: url(${blog.coverImageUrl})` : ''">
            <span v-if="!blog.coverImageUrl" class="no-image">博客</span>
          </div>
          <div class="blog-content">
            <div class="blog-meta">
              <span class="blog-type">{{ blog.blogType?.typeName || '未分类' }}</span>
              <span class="blog-date">{{ new Date(blog.createTime).toLocaleDateString() }}</span>
            </div>
            <h3 class="blog-title">{{ blog.title }}</h3>
            <p class="blog-summary">{{ blog.summary || (blog.content ? blog.content.replace(/<[^>]+>/g, '').substring(0, 120) + '...' : '') }}</p>
            <div class="blog-footer">
              <div class="blog-author">{{ blog.user?.name || '未知作者' }}</div>
              <div class="blog-stats">
                <span class="blog-likes">{{ blog.likes || 0 }} 赞</span>
                <span class="blog-comments">{{ blog.comments || 0 }} 评论</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div v-else class="loading-container">
        <div class="loading-spinner"></div>
      </div>
    </section>
    
    <!-- 加入 -->
    <section class="join-section">
      <div class="join-content">
        <h2 class="join-title">准备好分享您的故事了吗？</h2>
        <p class="join-description">
          加入我们的博客平台，开始记录和分享您的想法与经验。
        </p>
        <router-link to="/register" class="btn btn-accent">立即注册</router-link>
      </div>
    </section>
  </DefaultLayout>
</template>

<style>
/* 横幅区域 */
.banner-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 3rem;
  padding: 3rem 0 5rem;
  align-items: center;
  position: relative;
  overflow: hidden;
  background: linear-gradient(120deg, rgba(74, 111, 165, 0.1), rgba(217, 100, 43, 0.1));
  border-radius: 16px;
  margin-bottom: 4rem;
}

.banner-title {
  font-size: 2.8rem;
  line-height: 1.2;
  margin-bottom: 1.5rem;
  font-weight: 700;
  color: var(--text-color);
}

.banner-description {
  font-size: 1.2rem;
  line-height: 1.6;
  margin-bottom: 2rem;
  color: var(--text-light);
}

.banner-actions {
  display: flex;
  gap: 1rem;
}

.banner-decoration {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.decoration-circle {
  position: absolute;
  width: 180px;
  height: 180px;
  border-radius: 50%;
  background-color: rgba(74, 111, 165, 0.2);
  top: 20%;
  left: 20%;
}

.decoration-square {
  position: absolute;
  width: 120px;
  height: 120px;
  background-color: rgba(217, 100, 43, 0.2);
  border-radius: 16px;
  bottom: 30%;
  right: 25%;
  transform: rotate(45deg);
}

.decoration-dots {
  position: absolute;
  width: 150px;
  height: 150px;
  background-image: radial-gradient(var(--text-light) 2px, transparent 2px);
  background-size: 15px 15px;
  top: 40%;
  right: 10%;
}

/* 分类部分 */
.section {
  margin-bottom: 4rem;
  width: 100%;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2rem;
}

.section-title {
  font-size: 1.8rem;
  font-weight: 600;
  color: var(--text-color);
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 60px;
  height: 3px;
  background-color: var(--accent-color);
}

.view-all {
  font-size: 1rem;
  font-weight: 500;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
  margin-top: 2rem;
}

.category-card {
  background: var(--card-bg, #ffffff);
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid var(--border-color, #eaeaea);
}

.category-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
  border-color: var(--primary-color, #4a6fa5);
}

.category-content {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.category-name {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--text-primary, #2c3e50);
  margin: 0;
}

.category-info {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  color: var(--text-secondary, #666);
  font-size: 0.9rem;
}

.category-author {
  color: var(--primary-color, #4a6fa5);
  font-weight: 500;
}

.category-count {
  background-color: var(--tag-bg, #f0f2f5);
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  display: inline-flex;
  align-items: center;
  font-weight: 500;
}

/* 博客列表 */
.blogs-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 2rem;
  width: 100%;
}

.blog-card {
  border-radius: 8px;
  overflow: hidden;
  background: white;
  box-shadow: var(--card-shadow);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.blog-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.blog-image {
  height: 180px;
  background-color: var(--background-dark);
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-image {
  color: white;
  font-size: 1.5rem;
  font-weight: 500;
}

.blog-content {
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.blog-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1rem;
  font-size: 0.875rem;
}

.blog-type {
  color: var(--primary-color);
  font-weight: 600;
}

.blog-date {
  color: var(--text-light);
}

.blog-title {
  font-size: 1.25rem;
  margin-bottom: 0.75rem;
  line-height: 1.4;
}

.blog-summary {
  font-size: 0.95rem;
  line-height: 1.6;
  color: var(--text-light);
  margin-bottom: 1.5rem;
  flex: 1;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.blog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
  padding-top: 1rem;
  border-top: 1px solid var(--border-color);
}

.blog-author {
  font-weight: 500;
}

.blog-stats {
  display: flex;
  gap: 1rem;
  color: var(--text-light);
  font-size: 0.875rem;
}

/* 加入部分 */
.join-section {
  background-color: var(--primary-color);
  border-radius: 8px;
  padding: 3rem;
  text-align: center;
  color: white;
  width: 100%;
  margin: 2rem 0;
}

.join-title {
  font-size: 2rem;
  margin-bottom: 1rem;
}

.join-description {
  font-size: 1.1rem;
  margin-bottom: 2rem;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
  opacity: 0.9;
}

/* 加载动画 */
.loading-container {
  display: flex;
  justify-content: center;
  padding: 3rem 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(74, 111, 165, 0.2);
  border-radius: 50%;
  border-top-color: var(--primary-color);
  animation: spin 1s linear infinite;
}

@keyframes spin {
  100% {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 992px) {
  .banner-section {
    grid-template-columns: 1fr;
    gap: 2rem;
    text-align: center;
  }
  
  .banner-title {
    font-size: 2.2rem;
  }
  
  .banner-actions {
    justify-content: center;
  }
  
  .banner-decoration {
    order: -1;
  }
  
  .section-title::after {
    left: 50%;
    transform: translateX(-50%);
  }
}

@media (max-width: 768px) {
  .section {
    margin-bottom: 3rem;
  }
  
  .section-header {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .join-section {
    padding: 2rem;
  }
  
  .join-title {
    font-size: 1.75rem;
  }
  
  .join-description {
    font-size: 1rem;
  }
  
  .categories-grid {
    grid-template-columns: 1fr;
  }
  
  .category-card {
    padding: 1.25rem;
  }
}

/* 暗黑模式 */
@media (prefers-color-scheme: dark) {
  .category-card {
    --card-bg: #1a1a1a;
    --border-color: #333;
    --text-primary: #e1e1e1;
    --text-secondary: #999;
    --tag-bg: #333;
  }
}
</style> 